package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import pojo.Categories;
import util.DBUtils;
import dao.CategoriesDao;

public class CategoriesDaoImpl implements CategoriesDao {
	public CategoriesDaoImpl() {
	}

	public CategoriesDaoImpl(String str) {
	}
	@Override
	public int add(Categories categories) {
		String sql = "insert into categories(id,type) values(?,?)";
		PreparedStatement pst = null;
		Connection con = null;
		
		int m = 0;
		try {
			con = DBUtils.createConnection();
			pst = con.prepareStatement(sql);
			pst.setString(1, categories.getId());
			pst.setString(2, categories.getType());
			m = pst.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} 
		finally {
			DBUtils.close(con, pst, null);
		}
		return m;
	}

	@Override
	public int delete(String id) {
		return 0;
	}

	@Override
	public int update(Categories t) {
		return 0;
	}

	@Override
	public Categories load(String id) {
		Categories categories = null;
		String sql = "select * from CATEGORIES where id=?";
		PreparedStatement pst = null;
		ResultSet rs =null;
		Connection con = null;
		try {
			con = DBUtils.createConnection();
			pst = con.prepareStatement(sql);
			pst.setString(1, id);
			rs = pst.executeQuery();
			if(rs.next()) {
				String id1 = rs.getString("id");
				String type = rs.getString("type");
				categories = new Categories(id, type);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally{
			DBUtils.close(con, pst, rs);
		}
		return categories;
	}

	@Override
	public List<Categories> findAll() {
		List<Categories> list=new ArrayList<Categories>();
		String sql = "select * from CATEGORIES";
		PreparedStatement pst = null;
		ResultSet rs =null;
		Connection con = null;
		try {
			con = DBUtils.createConnection();
			pst = con.prepareStatement(sql);
			rs = pst.executeQuery();
			Categories categories = null;
			while (rs.next()) {
				String id = rs.getString("id");
				String type = rs.getString("type");
				categories = new Categories(id, type);
				list.add(categories);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally{
			DBUtils.close(con, pst, rs);
		}
		return list;
	}
}
